/*
 * ContactFormController.java
 *
 * Created on October 30, 2008, 1:35 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.vacuela.publishmx.web.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.util.WebUtils;
import org.vacuela.publishmx.constant.Constants;
import org.vacuela.publishmx.context.ServiceContext;
import org.vacuela.publishmx.context.ServiceContextImpl;
import org.vacuela.publishmx.domains.Contact;
import org.vacuela.publishmx.domains.ContactNumber;
import org.vacuela.publishmx.domains.Group;
import org.vacuela.publishmx.services.ContactBookService;
import org.vacuela.publishmx.util.PublishUtil;
import org.vacuela.publishmx.web.bean.ContactForm;
import org.vacuela.publishmx.web.bean.UserSession;

/**
 *
 * @author nestor.carrasco
 */
public class ContactFormController extends SimpleFormController {    
    
    private ContactBookService bookSvc;   
    
    
    /** Creates a new instance of GroupFormController */
    public ContactFormController() {
        setSessionForm(true);
        setValidateOnBinding(false);
        setCommandName("contactForm");
        setFormView("contact/addContact");
    }
    
     protected Map referenceData(HttpServletRequest request) throws Exception {
        Map model = new HashMap();
        ServiceContext context = new ServiceContextImpl();
        UserSession userSession = (UserSession)WebUtils.getRequiredSessionAttribute(request,Constants.USER_SESSION_DATA);
        context.setAttribute("userId", userSession.getUserDomain().getId());
        this.bookSvc.getGroupsByUserId(context);
        List<Group> myGroupsList  = (List<Group>)context.getAttribute("groupList");
        model.put("myGroupList",myGroupsList);
        
        String groupId = PublishUtil.checkNull(request.getParameter("groupAction"),"");
        context.setAttribute("groupId",groupId);
        bookSvc.getContactByGroupId(context);
         List<Contact> lstContact = ( List<Contact> )context.getAttribute("lstContact");
         model.put("lstContact",lstContact);
        return model;
    }
    
     protected Object formBackingObject(HttpServletRequest request) throws Exception {
        String contactId = PublishUtil.checkNull(request.getParameter("contactAction"),"");
        UserSession userSession = (UserSession)WebUtils.getRequiredSessionAttribute(request,Constants.USER_SESSION_DATA);
         ContactForm cf = null;   
        
        if ( "".equals(contactId)){
            return new ContactForm();
        }
        else {
         
         ServiceContext context = new ServiceContextImpl();
             Contact contact = new Contact();
             contact.setId(new Integer(contactId));
             contact.setUserId(userSession.getUserDomain().getId());
             context.setAttribute("contactDomain",contact);
             this.bookSvc.getContactById(context);
             contact = (Contact)context.getAttribute("contact");
            return new ContactForm(contact);
          
        }
     }
     protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
			throws Exception {

		ContactForm contactForm = (ContactForm) command;
		Contact contact = contactForm.getContact();
		
		errors.setNestedPath("contact");
		getValidator().validate(contact, errors);
		errors.setNestedPath("");
                //if (contactForm.isNewContact()){
                    int countNumbers = contactForm.getCountNumbers();
                    String paramPrefix  ="";
                   
                    List lstNumber = new ArrayList();
                    for( int i = 0; i < countNumbers; i++){
                        ContactNumber contacNum = new ContactNumber();
                         if ( contactForm.isNewContact()){
                               paramPrefix =  "contactForm.";
                         }else{
                            String numAux = request.getParameter("contact.numbers["+ i +"].number");
                            if (numAux == null){
                                  paramPrefix =  "contactForm.";
                            }
                         }
                        String numTemp = request.getParameter(paramPrefix +"contact.numbers["+ i +"].number");
                        String mandTemp = request.getParameter(paramPrefix +"contact.numbers["+ i +"].mandatory");
                        String refTemp = request.getParameter(paramPrefix +"contact.numbers["+ i +"].reference");
                        String idTemp = request.getParameter(paramPrefix +"contact.numbers["+ i +"].id");
                        
                        contacNum.setNumber(numTemp);
                        contacNum.setMandatory( (mandTemp == null || mandTemp.equals(""))?"N":"Y" );
                        contacNum.setReference(refTemp); 
                        contacNum.setId( (idTemp == null || idTemp.equals(""))?-1: Integer.parseInt(idTemp) );
                        lstNumber.add(contacNum);
                        paramPrefix  ="";
                    }
                    contact.setNumbers(lstNumber);
               // }
                
                if ( contact.getGroupList() == null || contact.getGroupList().size() < 1 ){
                 errors.rejectValue( "contact.groupList","GROUP_LIST_REQUIRED",
					 "Please select at least one Group to Save the Contact.");                 
               }
               
                if ( contact.getNumbers() == null || contact.getNumbers().size() < 1 ){
                 errors.rejectValue( "contact.numbers","GROUP_NUMBERS_LIST_REQUIRED",
					 "One number must to be mandatory Please select one.");                 
               }
     }  
     
       protected ModelAndView onSubmit(
            HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
            throws Exception {
        UserSession userSession = (UserSession)WebUtils.getRequiredSessionAttribute(request,Constants.USER_SESSION_DATA);
   
     
        ContactForm contactForm = (ContactForm) command;
	Contact contact = contactForm.getContact();
        contact.setUserId(userSession.getUserDomain().getId());
        ServiceContext context = new ServiceContextImpl();
        context.setAttribute("contactDomain", contact);
        try {
              
                bookSvc.saveUpdateContact(context);          
              
        } catch (DataIntegrityViolationException ex) {
            errors.rejectValue("contact.contactId", "CONTACT_ID_ALREADY_EXISTS",
                    "Contact ID already exists: choose a different ID.");
            return showForm(request, response, errors);
        }
        return super.onSubmit(request, response, command, errors);
    }
     
     public void setContactBookService(ContactBookService svc){
         this.bookSvc = svc;
     }
    
}
